import { isFunction } from "@/utils/check"
import { getUrlParams } from "@/utils/utils"
import { delay, loadScript, useWebEnv, useWebEvn } from "../utils"

export default class Base {
  constructor(config = {}) {
    const { env, debug, adapter = {} } = config
    this.env = env
    this.adapter = adapter
    this.isDebug = debug
    this.isReady = false
    this.isLogin = false
    this.events = new Map()
    this.webEnv = useWebEnv()
    this.webEvn = useWebEvn()
    this.urlParams = getUrlParams()
    this.systemInfo = uni.getSystemInfoSync()
    this.loginTime = this.getSessionItem("login_time")
    this.cache()
  }

  async print() {
    return new Promise(async (resolve) => {
      const next = () => {
        console.log(
          "%c 页面地址 %c " + window.location.href + " ",
          "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;",
          "padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: #42c02e; font-weight: bold;"
        )
        console.log(
          `%c 设备环境 %c ${this.webEnv} `,
          "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;",
          "padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: #42c02e; font-weight: bold;"
        )
        console.log(
          `%c 业务环境 %c ${this.webEvn} `,
          "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;",
          "padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: #42c02e; font-weight: bold;"
        )

        resolve()
      }

      if (this.isDebug) {
        try {
          await loadScript("https://public-oss-file.zmaxfilm.com/zuimei-film-oss/js/eruda.js")
          await delay(100)
          if (!window._eruda || window._eruda?._isInit == false) {
            window._eruda = window.eruda
            window._eruda.init()
          }
          // eslint-disable-next-line no-empty
        } catch (error) {}
        next()
      } else {
        next()
      }
    })
  }

  cache() {
    // 记录加载时间
    const loadTime = this.getSessionItem("load_time")
    if (!loadTime) this.setSessionItem("load_time", Date.now())
    // 记录重定向次数
    const redirectCount = this.getSessionItem("redirect_count") || 0
    this.setSessionItem("redirect_count", Number(redirectCount) + 1)
    // 设置首次加载页面
    const cacheIndexUrl = this.getSessionItem("index_url")
    if (!cacheIndexUrl) {
      this.setSessionItem("index_full_url", window.location.href)
      this.setSessionItem("index_url", window.location.href.split("?")[0])
    }
    // 监听hash变化
    window.onhashchange = (event) => {
      const oldURL = event.oldURL.split("?")[0]
      this.setSessionItem("back_url", oldURL)
    }
    // 监听刷新浏览器
    let beforeUnloadTime = 0
    window.addEventListener("beforeunload", () => {
      beforeUnloadTime = new Date().getTime()
    })
    window.addEventListener("unload", () => {
      if (new Date().getTime() - beforeUnloadTime >= 5) {
        // this.setSessionItem("redirect_count", 0)
      }
    })
  }

  back() {
    const indexUrl = window.location.href.split("?")[0]
    const loadTime = this.getSessionItem("load_time")
    const cacheIndexUrl = this.getSessionItem("index_url")
    const redirectCount = this.getSessionItem("redirect_count")
    if (indexUrl == cacheIndexUrl && redirectCount > 1 && Date.now() - loadTime < 15000) {
      this.setSessionItem("redirect_count", 0)
      window.history.back()
    }
  }
  init() {
    return new Promise((resolve) => {
      this.isReady = true
      resolve()
    })
  }

  // 初始化
  async ready() {
    return new Promise(async (resolve, reject) => {
      await this.print()
      try {
        await this.init()
        resolve(this)
      } catch (error) {
        reject(error)
      }
    })
  }

  // SDK 准备完毕回调事件
  onReady(handler = () => {}) {
    if (this.isReady) {
      handler(this)
    } else {
      const handlers = this.events.get("ready")
      if (handlers) {
        handlers.push(handler)
      } else {
        this.events.set("ready", [handler])
      }
    }
  }

  // SDK 错误回调事件
  onError(handler = () => {}) {
    const handlers = this.events.get("error")
    if (handlers) {
      handlers.push(handler)
    } else {
      this.events.set("error", [handler])
    }
  }

  // SDK 触发回调事件
  emit(name, ...args) {
    let handlers = this.events.get(name)
    if (handlers) {
      handlers.slice().map((handler) => {
        if (typeof handler === "function") handler(...args)
      })
    }
  }

  // 检查SDK api是否存在
  checkApi(api = "") {
    return this.apiList.includes(api)
  }

  // 检查SDK是否准备完毕
  checkReady(params = {}) {
    return new Promise((resolve, reject) => {
      if (this.isReady) {
        resolve(this)
        this.successCallback(params)
      } else {
        // 再次初始化一次
        this.init()
          .then(() => {
            this.isReady = true
            resolve(this)
            this.successCallback(params, this)
          })
          .catch((err) => {
            reject(err)
            this.failCallback(params, err)
          })
      }
    })
  }

  // 检查SDK是否登录
  checkLogin(params = {}) {
    return new Promise((resolve, reject) => {
      this.checkReady({
        success: () => {
          if (this.isLogin) {
            resolve()
            this.successCallback(params)
          } else {
            this.login()
              .then((res) => {
                this.isLogin = true
                resolve(res)
                this.successCallback(params, res)
              })
              .catch((err) => {
                reject(err)
                this.failCallback(params, err)
              })
          }
        },
        fail: (err) => {
          reject(err)
          this.failCallback(params, err)
        }
      })
    })
  }

  successCallback(params, data) {
    isFunction(params.success) && params.success(data)
    isFunction(params.complete) && params.complete()
  }

  failCallback(params, err) {
    isFunction(params.fail) && params.fail(err)
    isFunction(params.complete) && params.complete()
  }

  log(str) {
    console.log(
      `%c ${this.webEvn} %c ${str} `,
      "padding: 2px 1px; border-radius: 3px 0 0 3px; color: #fff; background: #606060; font-weight: bold;",
      "padding: 2px 1px; border-radius: 0 3px 3px 0; color: #fff; background: #42c02e; font-weight: bold;"
    )
  }

  // 检查window对象是否存在
  checkWindowKey({ key = "", retry = 5, success = () => {}, fail = () => {} }) {
    if (retry > 0) {
      if (window[key]) success(window[key])
      else setTimeout(() => this.checkWindowKey({ key, retry: retry - 1, success, fail }), 200)
    } else {
      fail()
    }
  }

  // 设置登录时间
  setLoginTime() {
    const loginTime = this.getSessionItem("login_time")
    if (!loginTime) {
      this.setSessionItem("login_time", new Date().getTime())
    }
  }

  // 获取URL参数
  getUrlParams() {
    return getUrlParams() || {}
  }

  setSessionItem(name, value) {
    window.sessionStorage.setItem(`_auth_${name}`, value)
  }

  getSessionItem(name) {
    return window.sessionStorage.getItem(`_auth_${name}`)
  }

  removeSessionItem(name) {
    window.sessionStorage.removeItem(`_auth_${name}`)
  }
}
